package cn.com.xiaoshoujia.wxpay.controller;

import java.util.SortedMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.xiaoshoujia.order.service.OrderService;
import cn.com.xiaoshoujia.utils.XMLUtil;
import cn.com.xiaoshoujia.wxpay.config.WeixinPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class WxpayNotify {

    private static final Logger logger = LoggerFactory.getLogger(WxpayNotify.class);

    private static final String RETURN_SUCCESS_MSG = "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";

    @Autowired
    private OrderService orderService;

    /**
     * @Author: yangrui
     * @Description: 微信回调
     * @Date: 下午2:27 2017/7/18
     */
    @RequestMapping(value = "/wxpay/notify")
    public Object notify(HttpServletRequest request, HttpServletResponse response,
                         @RequestBody(required = false) String requestBody) {
        logger.info("wxpayNotify requestBody={}", requestBody);
        SortedMap<String, String> map = XMLUtil.xml2map(requestBody);
        String result_sign = map.get("sign");
        map.remove("sign");

        String sign = WeixinPayConfig.buildSignature(map, WeixinPayConfig.mch_key);
        if (sign.equals(result_sign)) {
            logger.info("wx wxpayNotify requestBody={}", "验签成功");
            String result_code = map.get("result_code");
            if (result_code.equalsIgnoreCase("SUCCESS")) {
                String out_trade_no = map.get("out_trade_no");
                String total_fee = map.get("total_fee");
                String cluesId = map.get("attach");
                logger.info("wxpayNotify out_trade_no={}", out_trade_no);
                logger.info("wxpayNotify total_fee={}", total_fee);
                logger.info("wxpayNotify attach={}", cluesId);
                boolean aBoolean = orderService.notifyProcess(out_trade_no, total_fee, cluesId, requestBody);
                logger.info("wx 业务逻辑处理={}", aBoolean);

                return RETURN_SUCCESS_MSG;
            }
        }
        return null;
    }
}
